package com.wxpay.service.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.wxpay.WxPay;
import com.wxpay.common.PayException;
import com.wxpay.entity.Order;
import com.wxpay.service.OrderService;
import com.wxpay.service.WxPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.date.DateUtil;

/**
 * @Author worlt
 * @Date 2025/4/21 下午10:39
 */
@Service
public class WxPayServiceImpl implements WxPayService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private WxPay wxPay;

    /**
     * 微信小程序支付
     *
     * @param body   商品描述
     * @param money  支付金额
     * @param openId 用户openId
     * @return 返回支付所需参数
     */
    @Override
    public JSONObject minappPay(String body, String money, String openId) {
        JSONObject jsonObject = null;
        logger.info("发起微信支付 - 商品:{}, 金额:{}", body, money);
        
        try {
            // 创建订单
            Order order = orderService.add(body, money);
            if (order == null) {
                logger.error("微信支付失败 - 订单创建失败");
                throw new Exception("订单保存失败");
            }
            
            // 调用微信支付
            String outTradeNo = order.getOrderNo();
            com.alibaba.fastjson.JSONObject wxResult = wxPay.jsapiPay(outTradeNo, money, body, openId);
            
            if (wxResult != null) {
                // 转换返回结果
                jsonObject = new JSONObject();
                for (String key : wxResult.keySet()) {
                    jsonObject.set(key, wxResult.get(key));
                }
                
                // 添加订单号到返回结果
                jsonObject.set("outTradeNo", outTradeNo);
                logger.info("微信支付下单成功 - 订单号:{}", outTradeNo);
            } else {
                logger.error("微信支付下单失败 - 订单号:{}", outTradeNo);
            }
        } catch (PayException e) {
            logger.error("微信支付异常 - {}", e.getMessage());
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            logger.error("系统异常 - {}", e.getMessage());
            e.printStackTrace();
            return null;
        }
        
        return jsonObject;
    }
}
